package engine.display.newAttack
{
	import com.greensock.TweenMax;
	
	import engine.GameData;
	import engine.data.ModelLocator;
	import engine.data.SceneObject;
	import engine.display.newAttack.vo.AttackVo;
	import engine.display.newAttack.vo.FightInfoVo;
	import engine.display.newAttack.vo.FightPetInfoVo;
	import engine.flag.GameDefine;
	import engine.flag.ResourcesPath;
	import engine.newUi.ActorPropertyLogic;
	import engine.newUi.MyPropertyLogic;
	import engine.scene.SceneChangeManager;
	import engine.scene.SceneManager;
	import engine.scene.SceneView;
	import engine.tip.TipsMainLogic;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.loader.SwfLoader;
	import newx.utils.ArrayUtils;
	import newx.utils.MemoryOptimise;
	import newx.utils.debug.IO;
	
	/**
	 * 
	 * @author lw
	 * 
	 */
	public class AttackSceneView extends Sprite
	{
		private static const	_MaxSize : int	= 18;
		
		/**所有战斗对象**/
		private var _attackPlayers		:	Vector.<AttackPlayer>;
		
		private var _leftPet			:	AttackPet;
		
		private var _rightPet			: 	AttackPet;
		
		private var _damageSpace		:	MovieClip;
		
		private var _topEffectSpace	:	MovieClip;
		
		/**下层效果层*/
		private var _downEffectSpace	:	Sprite;
		
		/**人物层*/
		private var _npcSpace			:	Sprite;
		
		private var _sceneBG			:	Sprite;
		
		/**深度对象*/
		private var _depthArray		:	Array;
		
		private var _npcArr			:	Array;
		
		private var _fightInfoVos		:	Vector.<FightInfoVo>;
		
		private var _fightpetInfoVos	:	Vector.<FightPetInfoVo>;
		
		private var _bitMap			:	Bitmap;
		
		private var _leftphotoPlayer	: NxClip = new NxClip();
		
		private var _rightphotoPlayer	: NxClip = new NxClip();
		
		private var _leftphotoPet		: NxClip = new NxClip();
		
		private var _rightphotoPet		: NxClip = new NxClip();
		
		private var _bufferPropertyArr:Array =[];
		
		public static const PLAYERS_INIT_OVER : String = "players_init_over";
		
		public function AttackSceneView()
		{
			this.x = SceneChangeManager.attackSceneViewX;
			this.y = SceneChangeManager.attackSceneViewY;
			
			_bitMap = new Bitmap();
//			scaleX = .3;
//			scaleY = .3;
			
			init();
		}
		
		public function get rightPet():AttackPet
		{
			return _rightPet;
		}

		public function get leftPet():AttackPet
		{
			return _leftPet;
		}

		private function init():void
		{
			_depthArray 	= [];
			_npcArr 		= [];
			
			_sceneBG 		= new Sprite();
			_sceneBG.y		= 18;
			addChild( _sceneBG );
			
			TweenMax.to( _sceneBG, .001, {colorTransform:{tint:0x000000, tintAmount:0.5}});
			
			_downEffectSpace= new Sprite();
			addChild( _downEffectSpace);
			
			
			_npcSpace		= new Sprite();
			addChild(_npcSpace);
			
			
			_topEffectSpace = new MovieClip();
			addChild(_topEffectSpace);
			
			_damageSpace	= new MovieClip();
			addChild( _damageSpace );
			
			createPos();
		}
		
		private function initPlayerPhoto():void
		{
			initPhoto(_leftphotoPet);
			initPhoto(_rightphotoPet);
			initPhoto(_leftphotoPlayer);
			initPhoto(_rightphotoPlayer);
			
		}
		private function initPhoto(mc:NxClip):void
		{
			mc.source = ResManager.newResClass("Castle_Item_36") as MovieClip;
			var _img:NxClip = new NxClip();
			_img.x = mc.content["img2"].x;
			_img.y = mc.content["img2"].y;
			mc.content["img"] = _img
			mc.addChild(_img);
			_npcSpace.addChild( mc );
			
			switch(mc)
			{
				case _leftphotoPlayer:
					mc.x  = 10;
					mc.buttonMode = true;
					break;
				case _rightphotoPlayer:
					mc.x = 1100;
					mc.buttonMode = true;
					break;
				case _leftphotoPet:
					mc.x = 190;
					break;
				case _rightphotoPet:
					mc.x = 920;
					break;
			}
			mc.y = 80;
			_npcSpace.addChild( mc );
			mc.visible = false;
			mc.addEventListener(MouseEvent.CLICK,onClick);
			mc.addEventListener(MouseEvent.MOUSE_OVER,onOver);
			mc.addEventListener(MouseEvent.MOUSE_OUT,onOut);
			
		}
		private function onClick(e:MouseEvent):void
		{
			var mc : NxClip = e.currentTarget as NxClip;
			if(mc && mc.content["date"])
			{
				if(mc.content["date"] is String)
				{
					if(mc.content["date"] == ModelLocator.getInstance().scene.Role.getPlayerName())
					{
						MyPropertyLogic.getInstance().ui.showOrHide();					
					}
					else
					{
						ActorPropertyLogic.getInstance().lookOver(mc.content["date"]);
					}
				}
			}
		}
		private function onOver(e:MouseEvent):void
		{
			var mc : NxClip = e.currentTarget as NxClip;
			if(mc && mc.content["date"])
			{
				var showStr:String ="";
				if(mc.content["date"] is String)
				{
					TipsMainLogic.instance.showString(StaticIni.getSwfLangStr("UIString_1000035"));
				}
				else if(mc.content["date"] is FightPetInfoVo)
				{
					TipsMainLogic.instance.showWideString(getTipsStr(mc.content["date"] as FightPetInfoVo));
				}
				
			}
		}
		private function getTipsStr(_fightInfoVo:FightPetInfoVo):String
		{
			_bufferPropertyArr	 = 	[_fightInfoVo.petMaxHP,_fightInfoVo.petPhyDamage,_fightInfoVo.petPhyDef,_fightInfoVo.petMagDamage,_fightInfoVo.petMagDef,
				_fightInfoVo.petPhyDodgeProb,_fightInfoVo.petPhyHitProb,_fightInfoVo.petPhyWardProb,_fightInfoVo.petDePhyWardProb,
				_fightInfoVo.petPhyGuardProb,_fightInfoVo.petDePhyGuardProb,_fightInfoVo.petPhyVaProb,_fightInfoVo.petPhyVaDefProb];
			var tipstr:String = "";
			tipstr += StaticIni.getSwfLangStr("UIString_1000600")+_fightInfoVo.petlevel+"\n";
			tipstr += StaticIni.getSwfLangStr("UIString_1000599")+_fightInfoVo.petgrade+"\n";
			var index:int = 0;
			for(var i:String in _bufferPropertyArr)
			{
				var vaule:String = String(_bufferPropertyArr[int(i)]) ;
				if(vaule != "0")
				{
					index++;
					if(index  == 3)
					{
						index  =1;
					}
					var strID:String = (1+int(i))>=10?"Pet_Property_":"Pet_Property_0"
					var str:String =StaticIni.getSwfLangStrVar(strID+String(1+int(i)), [vaule] );
					var isHave:Boolean=false;
					
					tipstr += StaticIni.getSwfLangStrVar(strID+String(1+int(i)), [vaule] ) ;
					if(index%2 !=0 )
					{
						tipstr += "\n";
					}
					else
					{
						if(str.indexOf("%")!=-1)
						{
							isHave = true;
						}
						tipstr +=initStr(vaule,isHave);
					}
				}
				
			}
			return tipstr;
		}	
		private function initStr(val:String,isHave:Boolean=false):String
		{
			var addlen:int = Math.abs(8-(val.toString().length));
			var str:String= "";
			for(var i:int=0; i<addlen;i++)
			{
				str += "&nbsp;";
			}
			if(!isHave)
			{
				str += "&nbsp;&nbsp;";
			}
			return str;
		}
		private function onOut(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
		private function setPetattackInfo(petFightInfoVos: Vector.<FightPetInfoVo>):void
		{
			_leftphotoPet.visible = _rightphotoPet.visible = false;
			for each( var i:FightPetInfoVo  in petFightInfoVos)
			{
				var info:Array = [i.petid,0,i.petname,i.petlevel,i.petfightpower,i];
				if(i.pos>0)
				{
					_leftphotoPet.visible = (!AttackLogic.getInstance().isVideo())?true:false;
					_leftphotoPet.x = !_leftphotoPlayer.visible?10:190;
					setShowInfo(info,_leftphotoPet);
				}
				else
				{
					_rightphotoPet.visible = (!AttackLogic.getInstance().isVideo())?true:false;
					setShowInfo(info,_rightphotoPet);
				}
			}
		}
		private function setPlayerAttackInfo(fightInfoVos : Vector.<FightInfoVo>):void
		{
			var attackvo:AttackVo	=  AttackLogic.getInstance().attackVo;
			
			_leftphotoPlayer .visible = ((!AttackLogic.getInstance().isVideo())&&attackvo.leftPlayer!=""&&attackvo.rightPlayer!="")?true:false;
			setShowInfo([attackvo.leftModel,attackvo.leftClothemodel,attackvo.leftPlayer,attackvo.leftLevel,attackvo.leftTotalspeed,attackvo.leftPlayer],_leftphotoPlayer)
			_rightphotoPlayer .visible =((!AttackLogic.getInstance().isVideo())&&attackvo.leftPlayer!=""&&attackvo.rightPlayer!="")?true:false;
			setShowInfo([attackvo.rightModel,attackvo.rightClothemodel,attackvo.rightPlayer,attackvo.rightLevel,attackvo.rightTotalspeed,attackvo.rightPlayer],_rightphotoPlayer)
				
		}
		private function setShowInfo(info:Array,mc:NxClip):void
		{
			if(mc.content["img"])
			{
				(mc.content["img"]  as NxClip).source = ResourcesPath.getMiniHeadPic(int(info[0]),int(info[1]));
			}
			(mc.content["titleTxt2"] as TextField).htmlText = StaticIni.getSwfLangStrVar("Pet_Fight_Tips_Name",[info[2]]);
			(mc.content["infoTxt4"] as TextField).htmlText = StaticIni.getSwfLangStrVar("Pet_Fight_Tips_Level",[info[3]]);
			var strID:String = (info[5] is String)?"Pet_Fight_Tips_Speed":"Pet_Fight_Tips_FightPower";
			(mc.content["titleTxt3"] as TextField).htmlText =  StaticIni.getSwfLangStrVar(strID,[info[4]]);
			mc.content["date"] = info[5];
		}
		private function createPos():void
		{
			_rightPet = new AttackPet( -1 , 19);
			_leftPet =  new AttackPet( 1 , 20);
			_npcSpace.addChild( _rightPet )
			_npcSpace.addChild( _leftPet )
			initPlayerPhoto();
			_attackPlayers = new Vector.<AttackPlayer>();
			
			var attackPlayer : AttackPlayer;
			for( var pos : int = 0; pos <= _MaxSize; pos ++ )
			{
				if( pos == 9 )
				{//中心点，没人的
//					continue;	
					_attackPlayers.push( null );
				}else
				{
					attackPlayer = new AttackPlayer( pos );
					
					_npcSpace.addChild( attackPlayer )
						
					_attackPlayers.push( attackPlayer );
				}
//				
//				attackPlayer = null;
			}
			_attackPlayers.push(_leftPet);
			_attackPlayers.push(_rightPet);
		}
		
		private function getSceneSwfStart():int
		{
			if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene) return 1;
			
			var roleX : int = - SceneManager.getInstance().norSceneView.x;
			
			var start : int = roleX / 100;
			
			if( start > 25 - 14 )
			{
				return 25 - 14;
			}
			return start;
		}
		
		private function getSceneSwfEnd():int
		{
			if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene) return 25;
			return 13;
		}
		
		/**
		 * 进入场景 
		 * @param e
		 * 
		 */		
		public function enterSceneByLoad( sceneModel : String ):void
		{
			IO.traceLog("开始加载战斗场景，当前时间"+getTimer());
			
			//加载战斗场景
//			if( "" != sceneModel )
//			{//说明需要加载场景
				var start : int = getSceneSwfStart();
				
				var stop : int = start + getSceneSwfEnd();
				
				var head	:String="scene_"//int(StaticIni.getIniObj("Scene_IsNewSceneLoading")["sceneModel"])?"scene_":"bscene_";
					
				var scenePieceWidth:int	=	100;
				if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene) scenePieceWidth	=	52;//1300/25
				
				
				//根据场景坐标，看加载什么地图
				for( var i : int = start; i < stop; i++ )
				{
					SwfLoader.StartLoad( "res/scenes/" + head + sceneModel + "_" + i + ".swf", null,onComplete,[i] );
				}
				
				
				function onComplete( swf : MovieClip, pList : Array ):void
				{
					if(swf)
					{
						swf.x = ( pList[0] - start ) * scenePieceWidth;
						_sceneBG.addChild( swf );
					}
				}
//			}else
//			{
//				//特殊处理
//				_sceneBG.addChild( SceneManager.getInstance().norScetneView.view );
//			}
		}
		
		public function enterScene( sceneModel : String, isLoad : Boolean ):void
		{
			IO.traceLog("开始加载战斗场景，当前时间"+getTimer());
			
			if( !isLoad )
			{
				_bitMap = new Bitmap( new BitmapData( 1280, 768, false, 0 ));
				
				var rect : Rectangle = _bitMap.bitmapData.rect;
				var norSceneView : SceneView = SceneManager.getInstance().norSceneView;
				
				var sceneX : int = norSceneView.x > -600 ? -600 : norSceneView.x;
				
//				//后景
//				rect.x = Math.min( - sceneX + norSceneView.backSceneView.x + SceneChangeManager.getGameMinWidhtOffsize(), 2500 - 1380 );
//				_bitMap.bitmapData.copyPixels( norSceneView.backSceneView.sceneBitMap.bitmapData, rect, new Point( 0, 0) );
				
				//中景
				rect.x = Math.min( - sceneX + SceneChangeManager.getGameMinWidhtOffsize(), 2500 - 1280 );
				_bitMap.bitmapData.copyPixels( norSceneView.sceneBitMap.bitmapData, rect, new Point( 0, 0) );
				
				//特殊处理
				_sceneBG.addChild( _bitMap );
				
				rect = null;
			}else
			{
				enterSceneByLoad( sceneModel );
			}
		}
		
		/**
		 * 离开场景 
		 * @param e
		 * 
		 */		
		public function leaveScene():void
		{
			StageInfo.stage.frameRate = 12
//			return;
			clearPlayers();
			
			resetView( _sceneBG );
			
			if( _bitMap != null &&_bitMap.bitmapData!=null)
			{
				_bitMap.bitmapData.dispose();
			}
			
			if( null != parent )
			{
				this.parent.removeChild( this );
			}
//			IO.GC();
		}
		
		public function clearPlayers():void
		{
			MemoryOptimise.stopMovie(this);
			
			_npcArr		=	[];
			_depthArray =	[];
			
			for each( var attackPlayer : AttackPlayer in _attackPlayers )
			{
				if( attackPlayer == null )continue;
				attackPlayer.reset();
			}
			
			_leftPet.reset();
			_rightPet.reset();
			
			freeEffectSpace();
			resetView(_damageSpace);
		}
		
		public function freeEffectSpace():void
		{
			resetView( _topEffectSpace );
			resetView( _downEffectSpace );
		}
		
		private function resetView(val:Sprite):void
		{
			while (val.numChildren > 0)
			{
				val.removeChildAt(0);
			}		
		}
		
		public function createAttackPlayers( fightInfoVos : Vector.<FightInfoVo> ,fightpetInfoVos : Vector.<FightPetInfoVo>):void
		{
			_fightInfoVos = fightInfoVos.concat();
			_fightpetInfoVos = fightpetInfoVos.concat();
			
			setPlayerAttackInfo(fightInfoVos);
			setPetattackInfo(fightpetInfoVos);
			
			initAttackPet( _fightpetInfoVos );
			
			addEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
		
		private function onEnterFrame( evt : Event ):void
		{
			if( _fightInfoVos.length > 0 )
			{
				createAttackPlayer( _fightInfoVos.shift() );
			}else
			{
				removeEventListener( Event.ENTER_FRAME, onEnterFrame );
				onUpdateAttackDepth();
				
				dispatchEvent( new Event( PLAYERS_INIT_OVER ) );
			}
		}
		
		private function createAttackPlayer( fightInfoVo : FightInfoVo ):void
		{		
			var attackPlayer : AttackPlayer = getAttackPlayerFromPos( fightInfoVo.pos );
			
			attackPlayer.fightInfoVo = fightInfoVo;
			
			attackPlayer.visible = true;
			
			_depthArray.push( attackPlayer );
		
		}
		
		private function initAttackPet( fightInfoVos : Vector.<FightPetInfoVo> ):void
		{
			var pet : AttackPet;
			for each( var fightInfoVo : FightPetInfoVo in fightInfoVos )
			{
				if( fightInfoVo.petid != 0 )
				{
					if( fightInfoVo.pos == 1 )
					{
						pet = _leftPet;
					}else
					{
						pet = _rightPet;
					}
					pet.visible = true;
					pet.init( fightInfoVo);
				}
			}
		}
		
		/**
		 * 根据pos点获取对象 
		 * @param posVal
		 * @param isAll	：是否包括死亡对象
		 * @return 
		 */		
		public function getAttackPlayerFromPos( pos : int ):AttackPlayer
		{
			return _attackPlayers[ pos ];
		}
		
		public function getAttackPlayerFromPosArr( poses : Array ):Array
		{
			var attackPlayers  :Array = [];
			
			for each( var pos : int in poses )
			{
				attackPlayers.push( getAttackPlayerFromPos( pos ) );
			}
			
			return attackPlayers;
		}
		
		//移除对应站位点的信息
		public function removePlayer(npc:AttackPlayer,tObj:SceneObject):void
		{
			ArrayUtils.DeleteItem( _npcArr, tObj );
			ArrayUtils.DeleteItem( _depthArray, npc );

			onUpdateAttackDepth();
		}
		
		/**深度排序*/
		public function onUpdateAttackDepth():void
		{			
			if( 0 == _depthArray.length ) return;
			
			_depthArray.sortOn("y", Array.NUMERIC );
			
			var j : int	=	_depthArray.length ;
			
			var attackPlayer	:	AttackPlayer;
			
			while ( j-- )
			{
				attackPlayer =	_depthArray[ j ] as AttackPlayer;
				
				if( _npcSpace.getChildIndex( attackPlayer ) == j )
				{
					continue;
				}
				try
				{
					_npcSpace.setChildIndex( attackPlayer, ( j + 2 ) );
				} 
				catch(error:Error) {}
			}
		}
		
		/**获取一边的站位点*/
		public function getPosByTeam(team:int):Array
		{
			return [];
		}
		
		/**上层特效*/
		public function get topEffectSpace():MovieClip
		{
			return _topEffectSpace;
		}

		/**背景层*/
		public function get sceneBG():Sprite
		{
			return _sceneBG;
		}

		public function get damageSpace():MovieClip
		{
			return _damageSpace;
		}
	}
}
